package com.baizhi.controller;


import cn.hutool.core.util.RandomUtil;
import com.baizhi.dto.LoginFormDTO;
import com.baizhi.dto.Result;
import com.baizhi.entity.User;
import com.baizhi.entity.UserInfo;
import com.baizhi.service.IUserInfoService;
import com.baizhi.service.IUserService;
import com.baizhi.utils.RegexUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static cn.hutool.db.sql.SqlExecutor.query;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gange
 * @since 2023-04-06
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        // TODO 发送短信验证码并保存验证码
//        //查看用户是否注册
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("phone", phone);
//        User user = userService.getOne(queryWrapper);
//        String code = RandomUtil.randomNumbers(6);
//        System.out.println("code = " + code);
//        //没有注册 在数据库中添加
//        if (user == null) {
//            User user1 = new User();
//            user1.setPhone(phone);
//            LocalDateTime now = LocalDateTime.now();
//            user1.setCreateTime(now);
//            user1.setUpdateTime(now);
//            Random random = new Random();
//            String nickName = "user_";
//            for (int i = 0; i < 10; i++) {
//                nickName += random.nextInt(10);
//            }
//            user1.setNickName(nickName);
//            userService.save(user1);
//        }
//
//        String countKey = phone + ":count";
//        String codeKey = phone + ":code";
//
//        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
//
//        Integer count = (Integer) opsForValue.get(countKey);
//
//        if (count == null) {
//            opsForValue.set(countKey, 1,24, TimeUnit.HOURS);
//            count = 1;
//        }
//        if (count <= 3){
//            opsForValue.set(codeKey, code,5, TimeUnit.MINUTES);
//            opsForValue.increment(countKey);
//            return Result.ok();
//        }else {
//            return Result.fail("今日三次已用完,明天再来");
//        }
        return userService.gernateCode(phone);
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        // TODO 实现登录功能
//        String code = loginForm.getCode();
//        String password = loginForm.getPassword();
//        if (password == null && code == null) {
//
//            return Result.fail("登录失败");
//        } else if (code != null) {
//            ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
//            String s = (String) opsForValue.get(loginForm.getPhone() + ":code");
//            if (code.equals(s)) {
//
//                return Result.ok(session.getId());
//            } else {
//
//                return Result.fail("登录失败");
//            }
//        } else if (password != null) {
//            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("phone",loginForm.getPhone()).eq("password",password);
//            User user = userService.getOne(queryWrapper);
//            if (user == null){
//                return Result.fail("登录失败");
//            }else {
//                return Result.ok(session.getId());
//            }
//
//        }
//        return Result.ok();
        if(StringUtils.isEmpty(loginForm.getCode())){
            return userService.loginByPwd(loginForm,session.getId());
        }
        return userService.loginByCode(loginForm,session.getId());
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(){
        // TODO 实现登出功能
        return Result.fail("功能未完成");
    }

    @GetMapping("/me")
    public Result me(){
        // TODO 获取当前登录的用户并返回
        return Result.fail("功能未完成");
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }
}